import { ec as EC } from 'elliptic';

const ec = new EC('p256');

export interface PublicKey {
  x: string;
  y: string;
}

export interface Signature {
  r: string;
  s: string;
}

export interface TestAccount {
  address: string;
  privateKey: string;
  publicKey: PublicKey;
}

export interface TransactionRequest {
  from: string;
  to: string;
  value: number;
  nonce: string;
  signature: Signature;
  publicKey: PublicKey;
}

export interface TransactionResponse {
  hash: string;
  from: string;
  to: string;
  value: string;
  nonce: number;
  status: string;
  timestamp: number;
}

export interface BalanceResponse {
  address: string;
  balance: string;
}

export interface StateRootResponse {
  stateRoot: string;
}

export interface BlockResponse {
  height: number;
  hash: string;
  prevHash: string;
  merkleRoot: string;
  stateRoot: string;
  timestamp: number;
  transactionCount: number;
  transactions: TransactionResponse[];
}

export interface BlocksData {
  blocks: BlockResponse[];
}

export interface BlocksResponse {
  status: string;
  data: BlocksData;
}

// 浏览器兼容的SHA256哈希函数
export async function sha256(data: string): Promise<ArrayBuffer> {
  // 检查是否有 window.crypto.subtle
  if (typeof window !== 'undefined' && window.crypto && window.crypto.subtle) {
    const encoder = new TextEncoder();
    const dataBuffer = encoder.encode(data);
    return await window.crypto.subtle.digest('SHA-256', dataBuffer);
  } else if (typeof require !== 'undefined') {
    // Node.js 环境
    const crypto = require('crypto');
    const hash = crypto.createHash('sha256').update(data).digest();
    // 返回 ArrayBuffer
    return hash.buffer.slice(hash.byteOffset, hash.byteOffset + hash.byteLength);
  } else {
    throw new Error('SHA256 not supported in this environment');
  }
}

// 生成密钥对
export function generateKeyPair() {
  const keyPair = ec.genKeyPair();
  const privateKey = keyPair.getPrivate('hex');
  const publicKey = keyPair.getPublic();
  
  return {
    privateKey,
    publicKey: {
      x: publicKey.getX().toString('hex'),
      y: publicKey.getY().toString('hex'),
    }
  };
}

// 签名交易
export async function signTransaction(req: Omit<TransactionRequest, 'signature' | 'publicKey'>, account: TestAccount): Promise<TransactionRequest> {
  // 构造交易数据
  const txData = `${req.from}${req.to}${req.value}${req.nonce}`;
  
  // 使用浏览器原生的SHA256计算哈希
  const hashBuffer = await sha256(txData);
  const hashArray = new Uint8Array(hashBuffer);
  
  // 创建密钥对
  const keyPair = ec.keyFromPrivate(account.privateKey, 'hex');
  
  // 签名
  const signature = keyPair.sign(hashArray);
  
  return {
    ...req,
    signature: {
      r: signature.r.toString('hex'),
      s: signature.s.toString('hex'),
    },
    publicKey: account.publicKey,
  };
}

// 生成测试账户
export function generateTestAccounts(count: number): TestAccount[] {
  const accounts: TestAccount[] = [];
  
  for (let i = 1; i < count; i++) {
    const { privateKey, publicKey } = generateKeyPair();
    // 生成与后端测试一致的地址格式
    let address = "";
    if (i < 10) {
      address = `000000000000000000000000000000000000000${i}`;
    } else {
      address = `00000000000000000000000000000000000000${i}`;
    }
    
    accounts.push({
      address,
      privateKey,
      publicKey,
    });
  }
  
  return accounts;
}


